import { defineStore } from 'pinia'
import { TOKEN_KEY, TOKEN_PREFIX } from '@/constant'
import type { UserVO } from '@/request/api/user'
import { getUserApi, initUserVO } from '@/request/api/user'
import type { ResultType } from '@/type/type'
import { Code } from '@/request/code'
import icon from '@/assets/img/icon.png'
// 非持久化
export const useUserStore = defineStore(
  'user',
  () => {
    const user = ref<UserVO>(initUserVO())
    user.value.avatar = icon

    const token = ref<undefined | string>()

    const logout = () => {
      user.value = initUserVO()
      user.value.avatar = icon
      token.value = undefined
    }

    return {
      token,
      user,
      logout
    }
  },
  {
    persist: {
      key: TOKEN_KEY,
      storage: localStorage,
      paths: ['token'],
      afterRestore: async (state) => {
        if (state.store.token && state.store.user.id === 0) {
          await getUserApi().then((res: ResultType<UserVO>) => {
            if (res.code === Code.SUCCESS) {
              state.store.user = res.data
              state.store.token = state.store.user.token
            }
          })
        }
      }
    }
  }
)
